package org.jeecg.modules.iot.mqtt.server.service.impl;

import org.jeecg.modules.iot.mqtt.entity.MqttMessageJson;
import org.jeecg.modules.iot.mqtt.server.service.MqttSendCommand;
import org.jeecg.modules.iot.utils.JT808Utils;
import org.springframework.stereotype.Component;
import org.yzh.protocol.t808.T0100;
import org.yzh.protocol.t808.T8100;

import java.text.SimpleDateFormat;
import java.util.Date;

import static org.jeecg.modules.iot.util.MD5.generateSignature;

@Component("0100")

public class Command_0100_Send implements MqttSendCommand {
    @Override
    public void execute(MqttMessageJson mqttMessageJson, MqttMessageJson mqttMessageJsonReturn) throws Exception {
        long currentTimestamp = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
        Date date = new Date(currentTimestamp);
        String formattedTimestamp = sdf.format(date);
        T0100 msg = (T0100) JT808Utils.decode(mqttMessageJson.getData());
        /*判断车辆是否注册 如果没有注册就不能返回成功*/
        T8100 msgReturn= new T8100();
        msgReturn.setClientId(msg.getClientId());
        msgReturn.setSerialNo(msg.getSerialNo());
        msgReturn.setEncryption(0);
        msgReturn.setReserved(false);
        msgReturn.setMessageId(33024);

        /**/
        msgReturn.setResultCode(0);/*0成功1失败*/
        msgReturn.setToken("SUCCESS");
        String hex=JT808Utils.encode(msgReturn);

        mqttMessageJsonReturn.setId(mqttMessageJson.getId());
        mqttMessageJsonReturn.setCmd(JT808Utils.getResponseCommand(mqttMessageJson.getCmd()));
        mqttMessageJsonReturn.setData(hex);
        mqttMessageJsonReturn.setVersion(mqttMessageJson.getVersion());
        mqttMessageJsonReturn.setTimestamp(formattedTimestamp);
        mqttMessageJsonReturn.setSeq(mqttMessageJson.getSeq());
        mqttMessageJson.setId(mqttMessageJson.getId());
        String sign=generateSignature(mqttMessageJsonReturn.getId(),mqttMessageJsonReturn.getEnrc(),mqttMessageJsonReturn.getVender(),mqttMessageJsonReturn.getCmd(),mqttMessageJsonReturn.getTimestamp(),mqttMessageJsonReturn.getSeq(),mqttMessageJsonReturn.getData());
        mqttMessageJson.setSign(sign);

       /* String returnJson=objectMapper.writeValueAsString(mqttMessageJsonReturn);
        MqttMessage responseMessage = new MqttMessage(returnJson.getBytes());
        responseMessage.setQos(1);  // 设置消息的 QoS
        String topic=getTopic(mqttMessageJson.getId());
        mqttClient.publish(topic, responseMessage);*/
    }




}
